""""""
import json

from zonghe.caw import file_reader
from zonghe.caw.file_reader import read_config

"""
    数据库操作
"""
import pymysql

def connect(db_info):
    """
    建立数据库链接
    :param db_info: 数据库信息
    :return: 数据库连接
    """
    try:
        r = pymysql.connect(
            user=db_info["user"],
            password=db_info["pwd"],
            host=db_info["host"],
            port=db_info["port"],
            database=db_info["name"],
            charset='utf8'

        )
        print("连接数据库成功")
        return r
    except Exception as e:
        print("链接数据库异常",e)

def execute(conn,sql):
    """
    执行sql语句
    :param conn:数据库连接
    :param sql: sql语句
    :return:
    """
    try:
        cursor = conn.cursor() #获取游标
        cursor.execute(sql) #执行sql
        conn.commit() #提交commit
        r = cursor.fetchall()
        return r

    except Exception as e:
        print("执行sql语句",sql,"失败，异常信息为",e)

def dis_connect(conn):
    """
    断开连接
    :param conn: 要断开的链接
    :return:
    """
    try:
        conn.close()
        print("断开数据库连接成功")
    except Exception as e:
        print("断开数据库异常连接",e)

if __name__ == '__main__':
    db_info = json.loads(file_reader.read_config("db_info"))
    connect(db_info)
    r = execute(connect(db_info),"DELETE FROM member WHERE MobilePhone NOT LIKE '180%'")
    print(r)
    dis_connect(connect(db_info))